﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Consume;
using CarEdge.Infrastructure.Dto.Request.Customer;
using CarEdge.Infrastructure.Dto.Request.Dic;
using CarEdge.Infrastructure.Dto.Request.VIP;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Consume;
using CarEdge.Infrastructure.Dto.Response.VIP;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC.VIP;
using CarEdge.Service.Interface.VIP;
using Crm.Infrastructure.Tools;
using Microsoft.EntityFrameworkCore;

namespace CarEdge.Service.Instance.VIP
{
    [Inject_]
    public class VIP_Service : Base_Service, I_VIP_Service
    {
        public readonly VIP_IOC _customer_IOC;
        public VIP_Service(VIP_IOC customer_IOC)
        {
            _customer_IOC = customer_IOC;

        }
        /// <summary>
        /// 添加会员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> AddVIP(VIP_Request_Dto dto)
        {
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CPhone == dto.phone);
            if (iq.Any())
            {
                return Result(0, "手机号已存在");
            }
            var cdid = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2"&&d.DId!= "04021b0100d10030c63c01207ae71b47").OrderByDescending(d => d.DValue).Select(d => d.DId).FirstOrDefault();
            var cid = Config.GUID2();
            Customer customer = new Customer()
            {
                CId = cid,
                CAddress = dto.address,
                CAuthor = dto.record,
                CCreateTime = DateTime.Now,
                CDesc = dto.desc,
                CFollowTime = null,
                CLevel = 1,
                CName = dto.name,
                CNextTime = null,
                CPhone = dto.phone,
                CQq = dto.qq,
                //CvIsExpire = 0,
                CRecord = dto.record,
                CDid = cdid,
                CRemark = dto.remark,
                CRechargeAmount = 0,
                CResponsibility = null,
                CStatus = 1,
                CSchool = dto.school,
                CMileage = null,
                CVehicleModel = null,
                CSeasTime = null,
                CSource = null,
                CUpdateTime = null,
                CWechat = dto.wechat,
            };
            Vip vIP = new Vip()
            {
                VCid = cid,
                VCreateTime = DateTime.Now,
                VDid = cdid,
                VEffectiveTime = dto.effectivetime,
                VEndTime = DateTime.Now.AddDays(Convert.ToDouble(dto.effectivetime)),
                VId = Config.GUID2(),
                VIsExpire = 0,
                VRecharge = null,
                VActive = 0,
                VConsumption = 0,
                VActiveTime = null,
            };
            _customer_IOC._customer_EFCore.Add(customer);
            _customer_IOC._vIP_EFCore.Add(vIP);
        
            await _customer_IOC._customer_EFCore.SaveChangesAsync();   
            await _customer_IOC._vIP_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> AddVIPType(Dic_Request_Dto dto)
        {
            SysDictionary sysDictionary = new SysDictionary()
            {
                DId = Config.GUID(),
                DName = dto.name,
                DAuthor = dto.author,
                DCreateTime = DateTime.Now,
                DDtId = "6e78ff75ecf811ef9301902e1656e0d2",
                DExplain = dto.explain,
                DValue = dto.value,
                DUserCount = 0,
                DDesc = dto.desc,
                DUpdateAuthor = null,
            };
            _customer_IOC._dictionary_EFCore.Add(sysDictionary);
            var result = await _customer_IOC._dictionary_EFCore.SaveChangesAsync();
            return Result(result);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> bindactive()
        {
            DateTime now = DateTime.Now.Date;
            DateTime dateWithoutTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

            var sum =  _customer_IOC._vIP_EFCore.QueryAll(d => d.VActive == 1).ToList().Count();

            var today = _customer_IOC._vIP_EFCore.QueryAll(d => d.VActive == 1 && d.VActiveTime >= now).ToList().Count();

            return Result(1, "操作成功", data: new
            {
                sum,
                today
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> bindactiveEcharts()
        {
            DateTime now = DateTime.Now;
            int delta = DayOfWeek.Monday - now.DayOfWeek;
            if (delta > 0)
            {
                delta -= 7;
            }
            var start = now.AddDays(delta).Date;
            var list = _customer_IOC._consume_EFCore.QueryAll(d => d.CCreateTime >= start && d.CType == 0).Select(d => new Statistics_Response_Dto
            {
                vid = d.CVid,
                money = d.CMoney,
            }).ToList();
            var result = list.GroupBy(x => x.vid).Select(g => new Statistics_Response_Dto
            {
                vid = g.Key,
                money = g.Sum(x => x.money)
            }).OrderBy(x => x.money).Take(5).ToList();
            List<string> namelist = new List<string>();
            List<double?> moneylist = new List<double?>();
            result.ForEach(d =>
            {
                d.cid = _customer_IOC._vIP_EFCore.QueryAll(e => e.VId == d.vid).Select(e => e.VCid).FirstOrDefault();
                d.vname = _customer_IOC._customer_EFCore.QueryAll(e => e.CId == d.cid).Select(e => e.CName).FirstOrDefault();
            });
            var count = result.Count();
            var name1 = "";
            var name2 = "";
            var name3 = "";
            var name4 = "";
            var name5 = "";

            double? money1 = 0;
            double? money2 = 0;
            double? money3 = 0;
            double? money4 = 0;
            double? money5 = 0;

            if (count == 1)
            {
                name1 = result[0].vname;
                money1 = result[0].money;
            }
            if (count == 2)
            {
                name1 = result[0].vname;
                name2 = result[1].vname;
                money1 = result[0].money;
                money2 = result[1].money;
            }
            if (count == 3)
            {
                name1 = result[0].vname;
                name2 = result[1].vname;
                name3 = result[2].vname;
                money1 = result[0].money;
                money2 = result[1].money;
                money3 = result[2].money;
            }
            if (count == 4)
            {
                name1 = result[0].vname;
                name2 = result[1].vname;
                name3 = result[2].vname;
                name4 = result[3].vname;
                money1 = result[0].money;
                money2 = result[1].money;
                money3 = result[2].money;
                money4 = result[3].money;
            }
            if (count == 5)
            {
                name1 = result[0].vname;
                name2 = result[1].vname;
                name3 = result[2].vname;
                name4 = result[3].vname;
                name5 = result[4].vname;
                money1 = result[0].money;
                money2 = result[1].money;
                money3 = result[2].money;
                money4 = result[3].money;
                money5 = result[4].money;
            }




            if (result.Count == 1)
            {
                namelist.Add(name1!);
                moneylist.Add(money1!);
            }
            if (result.Count == 2)
            {
                namelist.Add(name1!);
                namelist.Add(name2!);
                moneylist.Add(money1!);
                moneylist.Add(money2!);
            }
            if (result.Count == 3)
            {
                namelist.Add(name1!);
                namelist.Add(name2!);
                namelist.Add(name3!);
                moneylist.Add(money1!);
                moneylist.Add(money2!);
                moneylist.Add(money3!);
            }
            if (result.Count == 4)
            {
                namelist.Add(name1!);
                namelist.Add(name2!);
                namelist.Add(name3!);
                namelist.Add(name4!);

                moneylist.Add(money1!);
                moneylist.Add(money2!);
                moneylist.Add(money3!);
                moneylist.Add(money4!);
            }
            if (result.Count == 5)
            {
                namelist.Add(name1!);
                namelist.Add(name2!);
                namelist.Add(name3!);
                namelist.Add(name4!);
                namelist.Add(name5!);
                moneylist.Add(money1!);
                moneylist.Add(money2!);
                moneylist.Add(money3!);
                moneylist.Add(money4!);
                moneylist.Add(money5!);
            }

            return Result(1, "操作成功", data: new
            {
                namelist = namelist,
                moneylist = moneylist,
            });
        }

        public async Task<Api_Response_Dto> bindconsumption()
        {
            DateTime now = DateTime.Now.Date;
            DateTime dateWithoutTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
            var sum = _customer_IOC._consume_EFCore.QueryAll(d => d.CType == 1).ToList().Count();
            var today = _customer_IOC._consume_EFCore.QueryAll(d => d.CType == 1 && d.CCreateTime >= now).ToList().Count();
            return Result(1, "操作成功", data: new
            {
                sum,
                today
            });
        }

        public async Task<Api_Response_Dto> BindSale()
        {
            DateTime now = DateTime.Now.Date;
            DateTime dateWithoutTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
            var sum = _customer_IOC._consume_EFCore.QueryAll(d => d.CType == 0).ToList().Select(d => d.CMoney).Sum();
            var today = _customer_IOC._consume_EFCore.QueryAll(d => d.CCreateTime >= dateWithoutTime && d.CType == 0).ToList().Select(d => d.CMoney).Sum();
            return Result(1, "操作成功", data: new
            {
                sum,
                today
            });
        }

        public async Task<Api_Response_Dto> BindTodayData()
        {
            DateTime now = DateTime.Now.Date;
            DateTime dateWithoutTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

            var recharge = await _customer_IOC._consume_EFCore.QueryAll(d => d.CCreateTime >= dateWithoutTime && d.CType == 0).Select(d => d.CMoney).SumAsync();
            var count = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCreateTime >= dateWithoutTime).ToList().Count();
            return Result(1, data: new
            {
                recharge,
                count,
            });
        }

        public async Task<Api_Response_Dto> bindvipcount()
        {
            DateTime now = DateTime.Now.Date;
            DateTime dateWithoutTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

            var sum = _customer_IOC._vIP_EFCore.QueryAll().ToList().Count();
            var today = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCreateTime >= dateWithoutTime).ToList().Count();
            return Result(1, data: new
            {
                sum,
                today,
            });
        }

        public async Task<Api_Response_Dto> Consumption(Consume_Request_Dto dto)
        {
            var last = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == dto.cid).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            //var c_did = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.cid).SingleOrDefault()!.CDid;
            //var key = Convert.ToDouble(_customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == c_did).SingleOrDefault()!.DValue);
            //var vipmoney = dto.money * key;
            if (last - dto.money < 0)
            {
                return Result(0, "没米了,请充值");
            }
            Consume consume = new Consume()
            {
                CVid = dto.cid,
                CCreateTime = DateTime.Now,
                CPid = dto.pid,
                CId = Config.GUID2(),
                CMoney = dto.money,
                CType = 1,
            };
            consume.CBalance = last - dto.money;
            _customer_IOC._consume_EFCore.Add(consume);
            await _customer_IOC._consume_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> DeleteVIP(Customer_Request_Dto dto)
        {
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CLevel == 1 && d.CId == dto.id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            _customer_IOC._customer_EFCore.Delete(iq.Single());
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> DeleteVIPType(VIP_Request_Dto dto)
        {
            var iq = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == dto.id).SingleOrDefault();
            _customer_IOC._dictionary_EFCore.Delete(iq!);
            await _customer_IOC._dictionary_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> ExpireVIP(VIP_Request_Dto dto)
        {
            var iq = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == dto.id);
            var iqq = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.id);
            if (!iq.Any() || !iq.Any())
            {
                return Result(0, "参数错误");
            }
            var vip = iq.Single();
            var cus = iqq.Single();
            //cus.CvIsExpire = 1;
            vip.VIsExpire = 1;
            vip.VEndTime = DateTime.Now;
            TimeSpan difference = Convert.ToDateTime(vip.VEndTime) - Convert.ToDateTime(vip.VCreateTime);
            vip.VEffectiveTime = Convert.ToInt32(difference.TotalDays);
            _customer_IOC._vIP_EFCore.Update(vip);
            _customer_IOC._vIP_EFCore.SaveChanges();

            _customer_IOC._customer_EFCore.Update(cus);
            _customer_IOC._customer_EFCore.SaveChanges();


            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> GetAllVIP(int page, int limit, string key, string type)
        {
            var alluser = _customer_IOC._sys_User_EFCore.QueryAll(d => d.UisBan == 0).ToList();
            var vip = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == type);
            if (!vip.Any())
            {
                var iq = _customer_IOC._customer_EFCore.QueryAll(out int total, page, limit, false, o => o.CCreateTime, d => d.CLevel == 1 && (d.CName!.Contains(key) || d.CDesc!.Contains(key)));
                var list = iq.ToList();
                var data = await iq.Select(d => new VIP_Response_Dto
                {
                    id = d.CId,
                    name = d.CName,
                    address = d.CAddress,
                    createtime = null,
                    mileage = d.CMileage,
                    phone = d.CPhone,
                    qq = d.CQq,
                    record = d.CResponsibility,
                    recharge_amount = d.CRechargeAmount,
                    school = d.CSchool,
                    status = d.CStatus,
                    effectivetime = null,
                    vehiclemodel = d.CVehicleModel,
                    vipid = d.CDid,
                    wechat = d.CWechat,
                }).ToListAsync();
                data.ForEach(d =>
                {

                    d.record = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.record).FirstOrDefault()!.Uname;
                    d.viplevel = _customer_IOC._dictionary_EFCore.QueryAll(e => e.DId == d.vipid).FirstOrDefault()!.DName;
                    d.createtime = _customer_IOC._vIP_EFCore.QueryAll(e => e.VCid == d.id).FirstOrDefault()!.VCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    d.recharge_amount = _customer_IOC._vIP_EFCore.QueryAll(e => e.VCid == d.id).FirstOrDefault()!.VRecharge;
                });
                //查询出来的数据在内存中 占用空间一般来说非常小

                return Result(1, "ok", new
                {
                    total,
                    data,
                    alluser,
                });

            }
            else
            {
                var iq = _customer_IOC._customer_EFCore.QueryAll(out int total, page, limit, false, o => o.CCreateTime, d => d.CLevel == 1 && ((d.CName!.Contains(key) || d.CDesc!.Contains(key)) && d.CDid == type));

                var data = await iq.Select(d => new VIP_Response_Dto
                {
                    id = d.CId,
                    name = d.CName,
                    address = d.CAddress,
                    createtime = null,
                    mileage = d.CMileage,
                    phone = d.CPhone,
                    qq = d.CQq,
                    record = d.CRecord,
                    recharge_amount = d.CRechargeAmount,
                    school = d.CSchool,
                    status = d.CStatus,
                    effectivetime = null,
                    vehiclemodel = d.CVehicleModel,
                    vipid = d.CDid,
                    wechat = d.CWechat,
                }).ToListAsync();
                data.ForEach(d =>
                {

                    d.record = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.record).FirstOrDefault()!.Uname;
                    d.viplevel = _customer_IOC._dictionary_EFCore.QueryAll(e => e.DId == d.vipid).FirstOrDefault()!.DName;
                    d.createtime = _customer_IOC._vIP_EFCore.QueryAll(e => e.VCid == d.id).FirstOrDefault()!.VCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    d.recharge_amount = _customer_IOC._vIP_EFCore.QueryAll(e => e.VCid == d.id).FirstOrDefault()!.VRecharge;
                });
                //查询出来的数据在内存中 占用空间一般来说非常小


                return Result(1, "ok", new
                {
                    total,
                    data,
                    alluser,
                });
            }

            //var iq = _customer_IOC._customer_EFCore.QueryAll(out int total, page, limit, false, o => o.CCreateTime, d => d.CLevel == 1 && (d.CName!.Contains(key) || d.CDesc!.Contains(key)));



        }

        public async Task<Api_Response_Dto> GetAllVIPType()
        {
            var iq = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2").OrderByDescending(d => d.DValue);
            var guid = Config.GUID();
            List<VIPType_Response_Dto> list = new List<VIPType_Response_Dto>();
            VIPType_Response_Dto dto = new VIPType_Response_Dto()
            {
                id = guid,
                name = "未知",
                explain = "所有会员"
            };

            var data = await iq.Select(d => new VIPType_Response_Dto
            {
                id = d.DId,
                name = d.DName,
                explain = d.DExplain,
                value = Convert.ToDouble(d.DValue),
                author = d.DAuthor,
                children = list

            }).ToListAsync();


            data.ForEach(d =>
            {
                d.author = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.author).FirstOrDefault()!.Uname;
                d.usecount = _customer_IOC._vIP_EFCore.QueryAll(e => e.VDid == d.id).Count();
            });
            data.Add(dto);
            data.Reverse();

            //查询出来的数据在内存中 占用空间一般来说非常小
            return Result(1, "ok", data);
        }

        public async Task<Api_Response_Dto> getbesthy()
        {
            DateTime now = DateTime.Now;
            int delta = DayOfWeek.Monday - now.DayOfWeek - 7;

            var start = now.AddDays(delta).Date;
            var iq = _customer_IOC._vIP_EFCore.QueryAll().OrderByDescending(d => d.VRecharge).FirstOrDefault();
            var sum = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == iq!.VId && d.CType == 0).Select(d => d.CMoney).Sum();
            var prev = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == iq!.VId && d.CType == 0 && d.CCreateTime >= start).Select(d => d.CMoney).Sum();
            var name = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == iq.VCid).FirstOrDefault()!.CName;
            return Result(1, "操作成功", new
            {
                name,
                sum,
                prev,
            });

        }

        public async Task<Api_Response_Dto> getexpirehycard()
        {

            var iq = _customer_IOC._vIP_EFCore.QueryAll().ToList().Count();
            var prev = _customer_IOC._vIP_EFCore.QueryAll(d => d.VIsExpire == 1).ToList().Count();
            double nb = Math.Round(Convert.ToDouble(prev) / Convert.ToDouble(iq), 2);
            double percentage = nb * 100;
            return Result(1, "操作成功", data: new
            {
                count = prev,
                percentage
            });
        }

        public async Task<Api_Response_Dto> gethycard()
        {
            DateTime now = DateTime.Now;
            int delta = DayOfWeek.Monday - now.DayOfWeek - 7;

            var start = now.AddDays(delta).Date;
            var iq = _customer_IOC._vIP_EFCore.QueryAll().ToList().Count();
            var prev = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCreateTime >= start).ToList().Count();
            double nb = Math.Round(Convert.ToDouble(prev) / Convert.ToDouble(iq), 2);
            double percentage = nb * 100;
            return Result(1, "操作成功", data: new
            {
                count = iq,
                percentage
            });
        }

        public async Task<Api_Response_Dto> GetLastYearRecharge()
        {
            int year = DateTime.Now.Year;
            var vips = await _customer_IOC._vIP_EFCore.QueryAll().ToListAsync();
            var lastvips = vips.Where(d => d!.VCreateTime!.Value.Year == year - 1).ToList();
            var thevips = vips.Where(d => d!.VCreateTime!.Value.Year == year).ToList();
            Statistics_Response_Dto lastdata = new Statistics_Response_Dto()
            {
                one = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 1).Select(d => d.VRecharge).Sum()),
                two = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 2).Select(d => d.VRecharge).Sum()),
                three = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 3).Select(d => d.VRecharge).Sum()),
                four = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 4).Select(d => d.VRecharge).Sum()),
                five = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 5).Select(d => d.VRecharge).Sum()),
                six = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 6).Select(d => d.VRecharge).Sum()),
                seven = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 7).Select(d => d.VRecharge).Sum()),
                eight = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 8).Select(d => d.VRecharge).Sum()),
                nine = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 9).Select(d => d.VRecharge).Sum()),
                ten = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 10).Select(d => d.VRecharge).Sum()),
                eleven = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 11).Select(d => d.VRecharge).Sum()),
                twelve = Convert.ToInt32(lastvips.Where(d => d!.VCreateTime!.Value.Month == 12).Select(d => d.VRecharge).Sum()),
            };
            Statistics_Response_Dto thedata = new Statistics_Response_Dto()
            {
                one = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 1).Select(d => d.VRecharge).Sum()),
                two = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 2).Select(d => d.VRecharge).Sum()),
                three = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 3).Select(d => d.VRecharge).Sum()),
                four = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 4).Select(d => d.VRecharge).Sum()),
                five = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 5).Select(d => d.VRecharge).Sum()),
                six = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 6).Select(d => d.VRecharge).Sum()),
                seven = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 7).Select(d => d.VRecharge).Sum()),
                eight = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 8).Select(d => d.VRecharge).Sum()),
                nine = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 9).Select(d => d.VRecharge).Sum()),
                ten = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 10).Select(d => d.VRecharge).Sum()),
                eleven = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 11).Select(d => d.VRecharge).Sum()),
                twelve = Convert.ToInt32(thevips.Where(d => d!.VCreateTime!.Value.Month == 12).Select(d => d.VRecharge).Sum()),
            };
            int[] last = new int[] { Convert.ToInt16(lastdata.one), Convert.ToInt32(lastdata.two), Convert.ToInt32(lastdata.three), Convert.ToInt32(lastdata.four), Convert.ToInt32(lastdata.five), Convert.ToInt32(lastdata.six), Convert.ToInt32(lastdata.seven), Convert.ToInt32(lastdata.eight), Convert.ToInt32(lastdata.nine), Convert.ToInt32(lastdata.ten), Convert.ToInt32(lastdata.eleven), Convert.ToInt32(lastdata.twelve) };
            int[] the = new int[] { Convert.ToInt16(thedata.one), Convert.ToInt32(thedata.two), Convert.ToInt32(thedata.three), Convert.ToInt32(thedata.four), Convert.ToInt32(thedata.five), Convert.ToInt32(thedata.six), Convert.ToInt32(thedata.seven), Convert.ToInt32(thedata.eight), Convert.ToInt32(thedata.nine), Convert.ToInt32(thedata.ten), Convert.ToInt32(thedata.eleven), Convert.ToInt32(thedata.twelve) };

            return Result(1, data: new
            {
                lastdata = last,
                thedata = the,
            });
        }

        public async Task<Api_Response_Dto> GetLastYearVIPAdd()
        {
            int year = DateTime.Now.Year;
            var vips = await _customer_IOC._vIP_EFCore.QueryAll().Select(d => d.VCreateTime).ToListAsync();
            var lastvips = vips.Where(d => d!.Value.Year == year - 1).ToList();
            var thevips = vips.Where(d => d!.Value.Year == year).ToList();
            Statistics_Response_Dto lastdata = new Statistics_Response_Dto()
            {
                one = lastvips.Where(d => d!.Value.Month == 1).Count(),
                two = lastvips.Where(d => d!.Value.Month == 2).Count(),
                three = lastvips.Where(d => d!.Value.Month == 3).Count(),
                four = lastvips.Where(d => d!.Value.Month == 4).Count(),
                five = lastvips.Where(d => d!.Value.Month == 5).Count(),
                six = lastvips.Where(d => d!.Value.Month == 6).Count(),
                seven = lastvips.Where(d => d!.Value.Month == 7).Count(),
                eight = lastvips.Where(d => d!.Value.Month == 8).Count(),
                nine = lastvips.Where(d => d!.Value.Month == 9).Count(),
                ten = lastvips.Where(d => d!.Value.Month == 10).Count(),
                eleven = lastvips.Where(d => d!.Value.Month == 11).Count(),
                twelve = lastvips.Where(d => d!.Value.Month == 12).Count(),
            };

            Statistics_Response_Dto thedata = new Statistics_Response_Dto()
            {
                one = thevips.Where(d => d!.Value.Month == 1).Count(),
                two = thevips.Where(d => d!.Value.Month == 2).Count(),
                three = thevips.Where(d => d!.Value.Month == 3).Count(),
                four = thevips.Where(d => d!.Value.Month == 4).Count(),
                five = thevips.Where(d => d!.Value.Month == 5).Count(),
                six = thevips.Where(d => d!.Value.Month == 6).Count(),
                seven = thevips.Where(d => d!.Value.Month == 7).Count(),
                eight = thevips.Where(d => d!.Value.Month == 8).Count(),
                nine = thevips.Where(d => d!.Value.Month == 9).Count(),
                ten = thevips.Where(d => d!.Value.Month == 10).Count(),
                eleven = thevips.Where(d => d!.Value.Month == 11).Count(),
                twelve = thevips.Where(d => d!.Value.Month == 12).Count(),
            };
            int[] last = new int[] { Convert.ToInt16(lastdata.one), Convert.ToInt32(lastdata.two), Convert.ToInt32(lastdata.three), Convert.ToInt32(lastdata.four), Convert.ToInt32(lastdata.five), Convert.ToInt32(lastdata.six), Convert.ToInt32(lastdata.seven), Convert.ToInt32(lastdata.eight), Convert.ToInt32(lastdata.nine), Convert.ToInt32(lastdata.ten), Convert.ToInt32(lastdata.eleven), Convert.ToInt32(lastdata.twelve) };
            int[] the = new int[] { Convert.ToInt16(thedata.one), Convert.ToInt32(thedata.two), Convert.ToInt32(thedata.three), Convert.ToInt32(thedata.four), Convert.ToInt32(thedata.five), Convert.ToInt32(thedata.six), Convert.ToInt32(thedata.seven), Convert.ToInt32(thedata.eight), Convert.ToInt32(thedata.nine), Convert.ToInt32(thedata.ten), Convert.ToInt32(thedata.eleven), Convert.ToInt32(thedata.twelve) };

            return Result(1, data: new
            {
                lastdata = last,
                thedata = the,
            });
        }

        public async Task<Api_Response_Dto> getmincard()
        {
            DateTime now = DateTime.Now;
            var iq = _customer_IOC._vIP_EFCore.QueryAll().OrderByDescending(d => d.VCreateTime).Take(3).ToList();
            List<VIP_Response_Dto> list = new List<VIP_Response_Dto>();
            iq.ForEach(d =>
            {

                TimeSpan timeDiff = (TimeSpan)(now - d.VCreateTime)!;
                VIP_Response_Dto dto = new VIP_Response_Dto()
                {
                    name = _customer_IOC._customer_EFCore.QueryAll(e => e.CId == d.VCid).FirstOrDefault()!.CName,
                    id = d.VCid,
                    time = FormatTimeDifference(timeDiff)
                };
                list.Add(dto);
            });
            return Result(1, "操作成功", list);
        }

        public static string FormatTimeDifference(TimeSpan timeDiff)
        {
            if (timeDiff.TotalMinutes < 60)
            {
                // 小于60分钟，显示分钟
                return $"{(int)timeDiff.TotalMinutes} 分钟前";
            }
            else if (timeDiff.TotalHours < 24)
            {
                // 小于24小时，显示小时
                return $"{(int)timeDiff.TotalHours} 小时前";
            }
            else
            {
                // 大于等于24小时，显示天数
                return $"{(int)timeDiff.TotalDays} 天前";
            }
        }


        public async Task<Api_Response_Dto> GetName(string phone)
        {
            var iqq = _customer_IOC._customer_EFCore.QueryAll(d => d.CPhone == phone);
            if (!await iqq.AnyAsync())
            {
                return Result(1, "操作成功", "无");
            }
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CPhone == phone).SingleOrDefault()!;
            var vipid = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == iq.CId).SingleOrDefault()!.VId;
            var balance = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == vipid);
            if (!balance.Any())
            {
                return Result(1, "操作成功", data: new
                {
                    name = iq.CName,
                    balance = 0
                });
            }
            return Result(1, "操作成功", data: new
            {
                name = iq.CName,
                balance = balance.OrderByDescending(d => d.CCreateTime).First().CBalance,
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetUserRechargeByid(string id)
        {
            var iq =await _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == id).OrderByDescending(d => d.CCreateTime).Select(d => new Consume_Response_Dto()
            {
                id = d.CId,
                type = d.CType,
                money = d.CMoney,
                pid = d.CPid,
                balance = d.CBalance,
                time = d.CCreateTime!.Value.ToString("yyyy-MM-dd:HH-mm")
            }).ToListAsync();
            var Accumulatedconsumption = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == id && d.CType == 1).Select(d => d.CMoney).Sum();
            var Accumulatedrecharge = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == id && d.CType == 0).Select(d => d.CMoney).Sum();
            var Balance = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == id).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            iq.ForEach(d =>
            {
                d.pname = _customer_IOC._sys_Product_EFCore.QueryAll(e => e.Pid == d.pid).Select(e => e.Pname).FirstOrDefault();
            });
            if (Balance == null)
            {
                Balance = 0;
            }
            return Result(1, "操作成功", data: new
            {
                data = iq,
                Accumulatedconsumption,
                Accumulatedrecharge,
                Balance
            });
        }

        public async Task<Api_Response_Dto> GetVIPById(string id)
        {
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == id && d.CLevel == 1);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var vip = iq.Single();
            VIP_Response_Dto data = new VIP_Response_Dto()
            {
                address = vip.CAddress,
                createtime = vip.CCreateTime?.ToString("yyyy-MM-dd:HH-mm"),
                name = vip.CName,
                phone = vip.CPhone,
                mileage = vip.CMileage,
                vehiclemodel = vip.CVehicleModel,
                qq = vip.CQq,
                vipid = vip.CDid,
                recharge_amount = vip.CRechargeAmount,
                viplevel = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == vip.CDid).Single().DName,
                record = _customer_IOC._sys_User_EFCore.QueryAll(d => d.Uid == vip.CRecord).Single().Uname,
                school = vip.CSchool,
                source = vip.CSource,
                status = vip.CStatus,
                id = vip.CId,
                wechat = vip.CWechat,
            };

            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "操作成功", data);
        }
        /// <summary>
        /// 通过会员id查充值/消费
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetVIPConsumeById(string id, int type)
        {
            var iq = await _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == id && (d.CType == type || type == 2)).OrderByDescending(d => d.CCreateTime).Select(d => new Consume_Response_Dto()
            {
                id = d.CId,
                type = d.CType,
                money = d.CMoney,
                pid = d.CPid,
                balance = d.CBalance,
                time = d.CCreateTime!.Value.ToString("yyyy-MM-dd:HH-mm")
            }).ToListAsync();
            iq.ForEach(d =>
            {
                d.pname = _customer_IOC._sys_Product_EFCore.QueryAll(e => e.Pid == d.pid).Select(e => e.Pname).FirstOrDefault();
            });
            return Result(1, "操作成功", iq);
        }

        public async Task<Api_Response_Dto> GetVIPTypeById(string id)
        {
            var time = DateTime.Now;
            var vips = _customer_IOC._vIP_EFCore.QueryAll(d => d.VDid == id).ToList();
            vips.ForEach(d =>
            {
                if (time > d.VEndTime)
                {
                    d.VIsExpire = 1;
                }
                _customer_IOC._vIP_EFCore.Update(d);
            });
            await _customer_IOC._vIP_EFCore.SaveChangesAsync();
            var iq = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var alluser = _customer_IOC._sys_User_EFCore.QueryAll(d => d.UisBan == 0).ToList();
            var type = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == id).SingleOrDefault();
            var allviptype = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2").ToList();
            var data = await _customer_IOC._vIP_EFCore.QueryAll(d => d.VDid == id && d.VIsExpire == 0).Select(d => new VIP_Response_Dto
            {
                id = d.VId,
                cid = d.VCid,
                did = d.VDid,
                effectivetime = d.VEffectiveTime,
                createtime = d.VCreateTime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                endtime = d.VEndTime!.Value.ToString("yyyy-MM-dd:HH-mm"),
            }).ToListAsync();
            data.ForEach(d =>
            {
                d.name = _customer_IOC._customer_EFCore.QueryAll(e => e.CId == d.cid).FirstOrDefault()!.CName;

            });
            return Result(1, data: new
            {
                list = data,
                type = type,
                allviptype = allviptype,
                alluser = alluser,
            });
        }

        public async Task<Api_Response_Dto> hfvip(VIP_Request_Dto dto)
        {
            var iq = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == dto.id);
            var iqq = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.id);
            if (!iq.Any() || !iq.Any())
            {
                return Result(0, "参数错误");
            }
            var vip = iq.Single();
            var cus = iqq.Single();
            vip.VIsExpire = 0;
            //cus.CvIsExpire = 0;
            vip.VEffectiveTime = dto.effectivetime;
            vip.VCreateTime = DateTime.Now;
            vip.VEndTime = DateTime.Now.AddDays(Convert.ToInt32(dto.effectivetime));
            _customer_IOC._vIP_EFCore.Update(vip);
            _customer_IOC._vIP_EFCore.SaveChanges();
            _customer_IOC._customer_EFCore.Update(cus);
            _customer_IOC._customer_EFCore.SaveChanges();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> Recharge(Consume_Request_Dto dto)
        {
            var cid = _customer_IOC._customer_EFCore.QueryAll(d => d.CPhone == dto.phone).SingleOrDefault()!.CId;
            var vid = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == cid).SingleOrDefault()!.VId;
            var last = _customer_IOC._consume_EFCore.QueryAll(d => d.CVid == vid).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            var customer = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == cid).SingleOrDefault();

            var vip = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == cid).Single();
            if (last == null || last == 0)
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = vid,
                    CCreateTime = DateTime.Now,
                    CBalance = dto.money,
                    CPid = null,
                    CMoney = dto.money,
                    CType = 0,
                };
                _customer_IOC._consume_EFCore.Add(consume);
            }
            else
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = vid,
                    CCreateTime = DateTime.Now,
                    CBalance = last + dto.money,
                    CPid = null,
                    CMoney = dto.money,
                    CType = 0,
                };
                _customer_IOC._consume_EFCore.Add(consume);
            }


            await _customer_IOC._consume_EFCore.SaveChangesAsync();

            vip.VRecharge = _customer_IOC._consume_EFCore.QueryAll(d => d.CType == 0 && d.CVid == vid).Select(d => d.CMoney).ToList().Sum();

            var did = "";
            var recharge = _customer_IOC._consume_EFCore.QueryAll(d => d.CType == 0 && d.CVid == vid).Select(d => d.CMoney).ToList().Sum();
            var types = _customer_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2").ToList();
            types.Select(d => d.DDesc).ToList().ForEach(d =>
            {
                if (recharge > Convert.ToDouble(d))
                {
                    did = types.Where(e => e.DDesc == d).FirstOrDefault()!.DId;
                }
            });
            vip.VDid = did;
            customer!.CDid = did;

            if (recharge > 0)
            {
                vip.VActive = 1;
                vip.VActiveTime = DateTime.Now;

            }
            _customer_IOC._customer_EFCore.Update(customer);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            _customer_IOC._vIP_EFCore.Update(vip);
            await _customer_IOC._vIP_EFCore.SaveChangesAsync();

            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> UpdateVIP(VIP_Request_Dto dto)
        {
            var iq = _customer_IOC._vIP_EFCore.QueryAll(d => d.VCid == dto.id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var vip = iq.Single();
            var customer = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == vip.VCid).Single();
            customer.CQq = dto.qq;
            customer.CAddress = dto.address;
            customer.CWechat = dto.wechat;
            customer.CPhone = dto.phone;
            customer.CSchool = dto.school;
            customer.CDesc = dto.desc;
            customer.CName = dto.name;
            _customer_IOC._customer_EFCore.Update(customer);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");

        }

        public async Task<Api_Response_Dto> bestuser()
        {
            var iq = await _customer_IOC._customer_EFCore.QueryAll().GroupBy(s => s.CResponsibility).Select(g => new VIP_Response_Dto
            {
                record = g.Key,
                count = g.Count()
            }).ToListAsync();
            iq.ForEach(d =>
            {
                d.record = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.record).FirstOrDefault()!.Uname;
            });
            var best = iq.OrderByDescending(d => d.count).FirstOrDefault();
            return Result(1, "操作成功", data: best);
        }

        public async Task<Api_Response_Dto> todayRecharge()
        {
            DateTime todayStart = DateTime.Today;
            var iq = await _customer_IOC._consume_EFCore.QueryAll(d => d.CCreateTime >= todayStart && d.CType == 0).Select(d => d.CMoney).SumAsync();
            return Result(1, "操作成功", data: iq);
        }
    }
}
